import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import demandApi from '@/apis/demand';
import dayjs from 'dayjs';

/**
 * 发布需求相关的Hook
 */
export function usePublishDemand() {
  const router = useRouter();
  const demandFormRef = ref(null);
  const activeStep = ref(0);
  const submitting = ref(false);

  // 需求表单数据
  const demandForm = reactive({
    title: '',
    description: '',
    budget: null,
    deadline: null,
    status: 3 // 默认立即发布
  });

  // 表单验证规则
  const rules = {
    title: [
      { required: true, message: '请输入需求标题', trigger: 'blur' },
      { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
    ],
    description: [
      { required: true, message: '请输入需求描述', trigger: 'blur' },
      { min: 10, max: 2000, message: '描述长度在 10 到 2000 个字符', trigger: 'blur' }
    ],
    budget: [
      { required: true, message: '请输入预算金额', trigger: 'blur' },
      { type: 'number', min: 0, message: '预算金额必须大于等于0', trigger: 'blur' }
    ],
    deadline: [
      { required: true, message: '请选择截止日期', trigger: 'change' }
    ]
  };

  // 禁用过去的日期
  const disabledDate = (time) => {
    return time.getTime() < Date.now();
  };

  // 格式化日期时间
  const formatDateTime = (date) => {
    if (!date) return '';
    return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
  };

  // 处理下一步
  const handleNext = () => {
    demandFormRef.value.validate((valid) => {
      if (valid) {
        activeStep.value = 1;
      } else {
        ElMessage.warning('请完善需求信息');
        return false;
      }
    });
  };

  // 提交需求
  const handleSubmit = async () => {
    try {
      submitting.value = true;
      
      // 提交到后端，格式化为后端需要的数据结构
      const response = await demandApi.addDemand({
        title: demandForm.title,
        description: demandForm.description,
        budget: demandForm.budget,
        deadline: demandForm.deadline,
        status: demandForm.status,
        auditRemark: ''
      });

      // 根据后端Result类的返回格式处理响应
      if (response.code === 200 || response.data.code === 200) {
        activeStep.value = 2;
      } else {
        ElMessage.error(response.message || response.data.message || '发布失败，请重试');
      }
    } catch (error) {
      ElMessage.error('发布失败，请稍后重试');
    } finally {
      submitting.value = false;
    }
  };

  // 取消操作
  const handleCancel = () => {
    ElMessageBox.confirm('确定要取消发布吗？已填写的内容将不会保存。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.back();
    }).catch(() => {
      // 取消操作
    });
  };

  // 返回需求列表
  const handleBackToList = () => {
    router.push('/my-demands');
  };

  // 发布另一个需求
  const handlePublishAnother = () => {
    activeStep.value = 0;
    // 重置表单
    demandForm.title = '';
    demandForm.description = '';
    demandForm.budget = null;
    demandForm.deadline = null;
    demandForm.status = 3;
    demandFormRef.value.resetFields();
  };

  return {
    // 引用和状态
    demandFormRef,
    activeStep,
    submitting,
    
    // 数据
    demandForm,
    rules,
    
    // 方法
    disabledDate,
    formatDateTime,
    handleNext,
    handleSubmit,
    handleCancel,
    handleBackToList,
    handlePublishAnother
  };
}